# -*- coding: utf-8 -*-
# created on 2017/3/29

from mathsolver.functions.base import *
from sympy.abc import n
from mathsolver.functions.mathematica.mathematicaSolve import MathematicaSimplify


# 数列{a_{n}}满足a_{n+1}+(-1)^{n}a_{n}=2n-1,则{a_{n}}的前60项和为()
class ShuLie_get_NumSums001(BaseFunction):
    def solver(self, *args):
        assert len(args) == 2
        seq = args[0].toSympy()
        num = args[1].toSympy()
        num_symbols = num.free_symbols
        assert not num_symbols
        known = self.known
        assert 'Sequations' in known
        assert known['Sequations']
        Seqs = known['Sequations']
        seq_name = seq.func
        ShuLie = self.search(str(seq_name))
        ShuLie.get_Init()
        ShuLie.Eqs_Update(Seqs)
        ShuLie.get_ShouXiang()
        ShuLie.get_DiTuiGongShi()
        ShuLie.get_Xiangs()
        DiTuiGongShi_Eqs = ShuLie.DiTuiGongShi_Eqs
        assert len(DiTuiGongShi_Eqs) == 1
        eq = DiTuiGongShi_Eqs[0]
        expr = eq[0] - eq[1]
        ShouXiangs = ShuLie.a1
        assert len(ShouXiangs) == 1
        ShouXiang = ShouXiangs[0]
        ShouXiang = ShouXiang[1]
        expr_xiangs = sl_Xiangs(expr)
        assert len(expr_xiangs) == 2
        max_index, min_index = sl_MaxMin_Index(expr)
        assert max_index - min_index == 1
        shulieNames = sl_ShuLie_Name(expr)
        assert len(shulieNames) == 1
        shulieName = sl_ShuLie_Name(expr)[0]
        an_values = [ShouXiang]
        nSums = ShouXiang
        for i in range(1, num):
            new_fn = expr
            new_fn = new_fn.subs({n: i})
            new_fn = new_fn.subs({shulieName(i): an_values[-1]})
            answers = solve(new_fn, shulieName(i + 1))
            answer = answers[0]
            nSums += answer
            an_values.append(answer)
        if len(str(nSums)) > 15:
            nSums = mathematicaSimplify().solver(basePoly(nSums)).output[0].toSympy()
        self.steps.append(["", "∴%s的前%s项和为%s" % (latex(seq), latex(num), latex(nSums))])
        self.output.append(baseNumber(nSums))
        self.label.add("求数列的和: 递归法")
        return self


class ShuLie_get_NumSums(BaseFunction):
    CLS = [ShuLie_get_NumSums001]

    def solver(self, *args):
        known = self.known
        r = None
        for cl in ShuLie_get_NumSums.CLS:
            try:
                new_known = dict(known)
                r = cl(new_known, verbose=True).solver(*args)
                break
            except Exception:
                pass
        if not r:
            raise 'try fail'
        return r
